﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using CookComputing.XmlRpc;
using BlogML.Xml;
using BlogML;
using CodeSane.MetaWeblog.Api;


namespace CodeSane.MetaWeblogToBlogML
{
    public class MetaWebblogToBlogMLConverter
    {
        string outPath= @"C:\Blogs";
        //string blogId = "codesane";
        string appKey = "codesane";
        string Url = @"http://codesane.com/blogs/metablog.ashx";
        string user = "anjoe";
        string password = "password";
        ICSMetaWeblog proxy = null;

        public MetaWebblogToBlogMLConverter()
        {
            proxy = XmlRpcProxyGen.Create<ICSMetaWeblog>();
            proxy.Url = Url;
        }

        public void ExportAllBlogs()
        {
            var blogs = proxy.getUsersBlogs(appKey, user, password);


            foreach (BlogInfo blog in blogs)
            {
                BlogMLBlog xblog = new BlogMLBlog();
                xblog.Title = blog.blogName;
                xblog.RootUrl = blog.url;
                IEnumerable<BlogMLCategory> categories;
                categories = GetCategories(blog);
                xblog.Categories.AddRange(categories);

                xblog.Posts.AddRange(GetPosts(blog,categories));
                using (StreamWriter writer = File.CreateText(Path.Combine(outPath, blog.blogid + ".xml")))
                {
                    BlogMLSerializer.Serialize(writer, xblog);
                }
            }
        }

        private IEnumerable<BlogMLPost> GetPosts(BlogInfo blog,IEnumerable<BlogMLCategory> categories)
        {
            var posts = from p in proxy.getRecentPosts(blog.blogid, user, password, 1000)
                        select BuildPost(p, categories);
            return posts;

        }

        private BlogMLPost BuildPost(Post p, IEnumerable<BlogMLCategory> categories)
        {
            BlogMLPost post = new BlogMLPost()
            {
                PostType=BlogPostTypes.Normal,
                Title = p.title,
                Content = new BlogMLContent()
                    {
                        Text = p.description,
                    },
                DateCreated = p.dateCreated,
                DateModified = DateTime.Today,
                ID = p.postid.ToString()
            };
            return post;
        }

        private IEnumerable<BlogMLCategory> GetCategories(BlogInfo blog)
        {
            
            var categories = from c in proxy.getCategories(blog.blogid, user, password)
                             select new BlogMLCategory() { ID = c.categoryid, Title = c.title, Description = c.description, Approved=true };
            return categories;
                                    
        }

      
    }
}
